#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
获取客服消息接口
"""

from flask import Blueprint, request, jsonify, current_app
from utils.logger import get_logger

kf_sync_msg_bp = Blueprint('kf_sync_msg', __name__)
logger = get_logger(__name__)


@kf_sync_msg_bp.route('/cgi-bin/kf/sync_msg', methods=['POST'])
def sync_msg():
    """获取客服消息"""
    try:
        # 获取请求参数
        access_token = request.args.get('access_token')
        
        logger.info("获取客服消息请求")
        
        # 参数验证
        if not access_token:
            logger.warning("缺少access_token参数")
            return jsonify({
                "errcode": 41001,
                "errmsg": "missing access_token parameter"
            }), 400
        
        # 获取请求体
        request_data = request.get_json()
        if not request_data:
            logger.warning("缺少请求体")
            return jsonify({
                "errcode": 41001,
                "errmsg": "missing request body"
            }), 400
        
        cursor = request_data.get('cursor', '')
        limit = request_data.get('limit', 1000)
        
        logger.info(f"同步消息参数 - cursor: {cursor}, limit: {limit}")
        
        # 获取数据管理器
        data_manager = current_app.data_manager
        
        # 验证访问令牌
        if not data_manager.validate_token(access_token):
            logger.warning("无效的access_token")
            return jsonify({
                "errcode": 40014,
                "errmsg": "invalid access_token"
            }), 400
        
        # 获取消息列表
        result = data_manager.get_messages(cursor=cursor, limit=limit)
        
        # 更新统计信息
        data_manager.update_stats(success=True)
        
        logger.info(f"获取客服消息成功 - 消息数量: {len(result.get('msg_list', []))}")
        
        return jsonify({
            "errcode": 0,
            "errmsg": "ok",
            "next_cursor": result.get('next_cursor', ''),
            "has_more": result.get('has_more', 0),
            "msg_list": result.get('msg_list', [])
        })
        
    except Exception as e:
        logger.error(f"获取客服消息失败: {e}")
        data_manager = current_app.data_manager
        data_manager.update_stats(success=False)
        
        return jsonify({
            "errcode": 500,
            "errmsg": "internal error"
        }), 500
